<template>
  <div class="private-letter">
    <div class="flex justify-between items-center">
      <p class="flex">
        <span @click="router.back()" class="yu-textColor-hover">私信</span>
        <i class="mr-2 ml-2"> > </i>
        <span>{{ route.query.name }}</span>
      </p>
      <span class="yu-textColor-hover">清空对话</span>
    </div>
    <ul class="h-150 yu-bgColor dialog-box overflow-y-scroll p-4" ref="monitor" v-scroll="isTopOut">
      <li class="mb-8 mt-2 w-full flex justify-around" v-if="loading">
        <van-loading/>
      </li>
      <li
          v-for="(item, index) in privateHistoryData"
          :key="item.id"
          class="relative mt-6 mb-6 flex w-full"
          :class="[
                store.userInfo.userId === item.fromUser.userId ? 'clear-both float-right flex-row-reverse' : 'clear-both float-left ']"
      >
        <p class="time"
           v-if="(index > 0 && timestampToSecondsMinutes(item.time -  privateHistoryData[index - 1].time, true) > 2) || index === 0">
          {{ timestampToYMD(item.time, 's') }}</p>
        <div class="w-15 h-15">
          <img class="w-15 h-15" :src="item.fromUser.avatarUrl" alt="">
        </div>
        <div
            class=" shadow-2xl opacity-100 pr-4 pl-4 pt-2 pb-2 flex flex-col justify-around rounded-md"
            :class="store.userInfo.userId === item.fromUser.userId ? 'mr-4 triangle-right yu-bgColor': 'triangle-left ml-4 yu-bgColor-active'"
        >
          <p class="mt-0 mb-0 text-justify">{{ item.msg.msg }}</p>
          <div v-if="item?.msg[judgmentType(item.msg.type).params]?.name" class="w-100 truncate">
            <at-type :resourceType="judgmentType(item.msg.type).model" :resource="item?.msg[judgmentType(item.msg.type).params]"/>
          </div>
          <!--  展示图片  -->
          <show-big-img
              v-if="item.msg.type === 16"
              :pics="[{originUrl: item.msg.picInfo.picUrl}]"
              :width="item.msg.picInfo.width/5"
              :height="item.msg.picInfo.height/5"
              :format="false"
          />
        </div>
      </li>
    </ul>
    <div class="yu-bgColor border-t-1 p-4">
      <van-field
          v-model="message"
          rows="2"
          autosize
          type="textarea"
          maxlength="200"
          show-word-limit
      />
      <div class="w-full flex justify-end mt-2">
        <yu-button @click="sendTextFn"> 发送</yu-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {getMsgPrivateHistory} from "@/api/message/index";
import ShowBigImg from '@/components/ShowBigImg/index.vue'
import YuButton from '@/components/YuButton/index.vue'
import AtType from '@/components/AtType/index.vue'
import { judgmentType } from "@/utils/index";
import {useRoute, useRouter} from "vue-router";
import {nextTick, reactive, ref, toRefs, watchEffect} from "vue";
import {useStore} from "@/store/index";
import {timestampToYMD, timestampToSecondsMinutes} from "@/utils/index";
import {sendText} from "@/api/share/index";
import {Toast} from "vant";

const route = useRoute()
const router = useRouter()
const store = useStore()
const monitor = ref()

const data = reactive({
  page: {
    limit: 10,
    before: 0
  },
  loading: false, // 加载
  flag: false, // 监听数据第一次加载是否完成
  privateHistoryData: [], // 聊天数据
  message: '' // 聊天框发送信息
})
const {privateHistoryData, loading, message} = toRefs(data)
// 获取私信内容
const getMsgPrivateHistoryFn = (height = null) => {
  // 开启loading
  data.loading = true
  getMsgPrivateHistory({uid: route.query.id, ...data.page}).then(res => {
    if (res.code === 200) {
      data.loading = false
      res.msgs = res.msgs.map(item => {
        return {
          ...item,
          msg: JSON.parse(item.msg)
        }
      })
      res.msgs = [...data.privateHistoryData, ...res.msgs].sort((a, b) => a.time - b.time)
      data.privateHistoryData = res.msgs
      // 刚进来页面后页面加载 before === 0的情况下才设置flag
      if (data.page.before === 0) data.flag = true
      // 用来定位请求后的聊天位置
      if (height) positioningPosition(height)
    }
    console.log(data.privateHistoryData)
  })
}
getMsgPrivateHistoryFn()

// 请求触顶 数据变，聊天位置不变
const positioningPosition = (height) => {
  // 需要延迟执行才能获取数据
  nextTick(() => {
    // 将当前元素的高度 减去 之前元素的高度 就是在请求数据之前数据的位置 将这个值赋值给 scrollTop(元素距离顶部的位置)
    monitor.value.scrollTop = monitor.value.scrollHeight - height
  })
}

watchEffect(() => {
  // 刚进入聊天框页面数据请求完毕后将 聊天框信息滚动到底部
  if (data.flag) {
    nextTick(() => {
      monitor.value.scrollTop = monitor.value.scrollHeight
      data.flag = false
    })
  }
})

// 监听是否触顶， 触顶请求数据
const isTopOut = (type, height) => {
  // 判断第一个数据的 time是否存在
  if (data.privateHistoryData[0].time && type) {
    data.page.before = data.privateHistoryData[0].time
    getMsgPrivateHistoryFn(height)
  }
}

// 发送私信
const sendTextFn = () => {
  if (data.message)
    sendText({user_ids: route.query.id, msg: data.message}).then(res => {
      let {code, newMsgs} = res
      if (code === 200) {
        newMsgs = newMsgs.map(item => {
          return {
            ...item,
            msg: JSON.parse(item.msg)
          }
        })
        console.log(newMsgs)
        data.message = ''
        data.privateHistoryData = [...data.privateHistoryData, ...newMsgs]
        nextTick(() => {
          monitor.value.scrollTop = monitor.value.scrollHeight
        })
        console.log(data.privateHistoryData)
      }
    })
  else Toast('请输入内容')
}


</script>

<style scoped lang="scss">
.triangle-right {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    right: -10px;
    top: 20px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-left: 10px solid v-bind('store.theme.bgColor');
    border-bottom: 10px solid transparent;
  }
}

.triangle-left {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    left: -10px;
    top: 20px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid v-bind('store.theme.HoverBgColor');
  }
}

.time {
  position: absolute;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
}

.van-loading {
  color: v-bind('store.theme.titleTextColor');
}

.van-field {
  border: v-bind('store.theme.titleTextColor') 2px solid;
}
</style>
